//js


//错误提示
function errAlert(msg, callback){
	
	(top.art || art).dialog({title:'错误',content:msg, icon:'error', ok:true, lock:true,resize:false, opacity:0.1, close: callback});
}

//警告提示
function wrnAlert(msg, callback){
	(top.art || art).dialog({title:'警告',content:msg, icon:'warning', ok:true, lock:true,resize:false, opacity:0.1, close: callback});
}

//成功提示
function okAlert(msg, callback){
	(top.art || art).dialog({content:msg, icon:'succeed', ok:true, lock:true,resize:false, opacity:0.1, close: callback});
}

//确认提示
function artConfirm(title, content, yes, no){
	if(typeof content == 'function'){
		yes = content;
		content = title;
		title = undefined;
	}
	(top.art || art).dialog({
		id: 'Confirm',
		icon: 'question',
		fixed:true,
		lock:true,
		resize:false,
		opacity:0.1,
		title:title,
		content:content,
		ok: function (here) {
			return yes.call(this, here);
		},
		cancel: !!no ? (function(here){return no.call(this, here);}) : true
	});
}

//加载指定页面的弹出窗口
function artWindow(winUrl, winTitle, winWidth, winHeight, onClosed){
	var artSettings = {
		title : winTitle,
		width : winWidth,
		height : winHeight,
		id : window.ART_DIALOG_WINDOW_ID || 'ART_DIALOG_WINDOW_ID',
		fixed : true,
		lock  : true,
		resize: false,
		opacity: 0.1, // 透明度
		close: onClosed
	};
	art.dialog.open(winUrl, artSettings);
}

//生成ligerGrid的参数
function ligerGridParam(param){
	var p = {};
	$.extend(p, {
		parms: [],
		//width: '99.5%',
		height: '99.5%',
		pageSizeOptions: [15, 20, 30, 50, 100],
		pageSize: 20,
		columnWidth: 125,
		checkbox:true,
		alternatingRow: false,
		allowHideColumn: false,
		root: "rows",
		record: "total",
		dataAction : 'server',
		usePager: true,
		enabledSort: false,
		rownumbers:true
	}, param);
	if(p.pageSize){
		p.pageSize = parseInt(p.pageSize);
	}
	if($.inArray(p.pageSize, p.pageSizeOptions) == -1){
		p.pageSizeOptions.push(p.pageSize);
	}
	return p;
}

//获取选中行的id
function getSelectedIds(ligerGrid, idField){
	var rows = ligerGrid.getSelecteds();
	if(rows.length==0){
		return [];
	}
	var ids = [];
	for(var i=0; i<rows.length; i++){
		ids.push(rows[i][idField]);
	}
	return ids;
}

//提交数据
function postData(url, data, confirmMsg, successMsg, callback){
	var func = function(){
		$.ajax({
			type: "POST",
			url: url,
			data: data,
			dataType: 'json',
			cache: false,
			traditional:true,
			success: function(data){
				if(successMsg){
					UiUtil.isSuccess(data, successMsg, function(){
						if(callback){callback.call(this, data, true);}
					},function(){
						if(callback){ callback.call(this, data, false); }
					});
				}else{
					if(callback){callback.call(this, data, true);}
				}
			}
		});
	};
	if(confirmMsg){
		artConfirm(confirmMsg, func);
	}else{
		func();
	}
}

//设置文本域只读
function setReadonly(obj){
	if(typeof(obj)=='string'){
		obj = $("#"+obj);
	}
	obj.prop("readonly", true);
	obj.css("ime-mode","disabled");
	obj.bind("keydown",function(e){return false;});
	obj.bind("paste",function(){return false;});
	obj.bind("dragenter", function(){return false;});
	obj.bind("contextmenu", function(){return false;});
	obj.bind("dragover",function(){return false;});
}

//创建下拉框
//返回创建的ligerComboBox对象
function createSelect(displayId, valueId, settings){
	var p = {};
	if(settings.tree){
		var treeSettings = {};
		$.extend(treeSettings, {idFieldName: 'id', textFieldName:'name', checkbox:false, isExpand:false}, settings.tree);
		settings.tree = treeSettings;
		p.treeLeafOnly=true;
		p.forbidTreeCancel=true;
		p.isTreeLeaf=function(node){return (node.isParent!==true && node.isParent!=='true');};
		if(!treeSettings.isAsync){
			p.onTreeAfterAppend=function(pNode, newdata, tree){
				if(newdata && newdata.length==1 && newdata[0].isemptyrow){
					return;
				}
				if(this._select_inited){
					return true;
				}
				this._select_inited = true;
				var initid = this.getInitValue();
				if(initid){
					var pn = tree.getDataByID(initid);
					if(pn){
						pn = tree.getParentTreeItem(pn);
						var nodes=[];
						while(pn){
							nodes.push(pn);
							pn = tree.getParentTreeItem(pn);
						}
						for(var i=nodes.length-1; i>=0; i--){
							tree.expand(nodes[i]);
						}
					}
				}
			};
		}
		p.render = function(val, text){
			var g=this,p=g.options, tree=g.treeManager;
			var pn = tree.getDataByID(val);
			var showText = '';
			if(pn){
				showText = pn[treeSettings.textFieldName];
				pn = tree.getParent(pn);
				while(pn){
					showText = pn[treeSettings.textFieldName]+' > '+showText;
					pn = tree.getParent(pn);
				}
			}
			return showText;
		};
	}
	$.extend(p, {
		defaultValue: "",
		defaultText: "---请选择---",
		selectBoxWidth: null,
		selectBoxHeight: 220,
		valueFieldID: valueId,
		textField: 'name',
		valueField:'id',
		initValue: null,
		initText: null,
		url: null
	}, settings);
	if(p.valueFieldID && p.initValue===null && p.initText===null){
		var v = $("#"+p.valueFieldID).val();
		if(v!=''){p.initValue = v;}
	}
	if(!p.onSuccess && !p.initValue){
		p.onSuccess = function(data){
			if(data.length==2 && data[0][this.options.textField]===this.options.emptyText){
				this.selectValue(data[1][this.options.valueField]);
			}
		};
	}
	return $("#"+displayId).ligerComboBox(p);
}

//创建多选下拉框
//返回创建的ligerComboBox对象
function createMultiSelect(displayId, valueId, settings){
	$.extend(settings, {
		isShowCheckBox: true,
		isMultiSelect: true
	});
	return createSelect(displayId, valueId, settings);
}

//弹出新页面上的选择列表
function createSelectPage(displayId, settings){
	var display = $('#'+displayId);
	if(!display.hasClass('select_page')){
		display.addClass('select_page');
	}
	display.click(function(){
		var p = {};
		$.extend(p, {
			url: null,
			title: '请选择',
			width: 750,
            height: 530,
            data: null,
            onClose: null
		}, settings);
		$.ligerDialog.open(p);
	});
}


/**
 * 格式化为指定小数位的文本
 * @param value 要格式化的数字
 * @param decimals 小数位，如果不指定则与number的小数位相同
 * @param thousandsSep 是否使用千位分隔符，默认不使用
 * @return
 */
function getDecimalNum(number, decimals, thousandsSep){
	var n = +number || 0,
		d = (typeof(decimals)==='undefined' || decimals===null ||  decimals < 0) ? -1 : decimals,
		c = d === -1 ? (n.toString().split('.')[1] || '').length : (isNaN(d = Math.abs(d)) ? 2 : d),
		s = n < 0 ? "-" : "",
		i = String(parseInt(n = Math.abs(n).toFixed(c))),
		j = i.length > 3 ? i.length % 3 : 0;
	if(thousandsSep===true){
		return s + (j ? i.substr(0, j) + ',' : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1,")
				+ (c ? '.' + Math.abs(n - i).toFixed(c).slice(2) : "");
	}
	return s + i + (c ? '.' + Math.abs(n - i).toFixed(c).slice(2) : "");
}


//从指定对象解析日期对象
//参数允许的类型包括：
//1.JavaScript的Date对象，直接返回
//2.GMT时间毫秒值，使用该值构造日期对象
//3.一个形如*Date(1406806223328)*的字符串，从中解析时间值构造日期对象
//4.一个标准格式的日期字符串，格式yyyy-MM-dd[ HH:mm:ss.SSS]
//5.一个其他可作为Date构造方法参数的数据[不同浏览器之间存在差异]
//返回：Date对象，如果不指定参数返回null
function parseDate(date){
	if(!date && date !== 0) return null;
	var int = parseInt;
	var vdate = date, rs;
	if(typeof(date) == 'number'){
		vdate = new Date(), vdate.setTime(date);
	}else if(typeof(date) == 'string'){
		if((rs = /^(\d+)$|^.*(?:Date\()(\d+)\).*$/g.exec(date))!=null){
			vdate = new Date(), vdate.setTime(int(rs[1]||rs[2]));
		}else if((rs = /^(\d{4})[-.\/](\d{1,2})[-.\/](\d{1,2})(?:\s(\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:\.(\d{1,3}))?)?)?)?$/g.exec(date))!=null){
			var methods = ['','setFullYear', 'setMonth', 'setDate', 'setHours', 'setMinutes', 'setSeconds', 'setMilliseconds'];
			for(vdate = new Date(), i=1; i<8; i++){
				if(i==2){//setMonth
					rs[i] ? (vdate[methods[i]](int(rs[i].replace(/^0/, ''))-1 , 1)) : vdate[methods[i]](0);
				}else{
					rs[i] ? (vdate[methods[i]](int(rs[i].replace(/^0/, '')))) : vdate[methods[i]](0);
				}
			}
		}
	}
	if(vdate instanceof Date){
		return vdate;
	}
	try{ return new Date(date); }catch (err){ return null;}
}

//格式化日期
//date 必须，日期对象
//format 格式，默认yyyy-MM-dd HH:mm:ss
function formatDate(date, format){
	date = parseDate(date);
	if(!date) return "";
	if(date instanceof Date && date.toString()!='Invalid Date'){
		format = format || "yyyy-MM-dd HH:mm:ss";
		var o = {
			"y+": date.getFullYear(),
			"M+": date.getMonth()+1,
			"d+": date.getDate(),
			"h+": date.getHours(),
			"H+": date.getHours(),
			"m+": date.getMinutes(),
			"s+": date.getSeconds(),
			"S+": date.getMilliseconds(),
			"W+": date.getDay(),
			"Q+": parseInt((date.getMonth()+3)/3)
		};
		return format.replace(/y+|M+|d+|h+|H+|m+|s+|S+|W+|Q+/g, function(){
			var a = arguments[0], b = a.length, a = a.substr(0,1)+'+', v = String(o[a]), c = v.length;
			if(c>2){
				return ('0000'+v).substr(c+4-b);
			}
			return c>b ? v : ('0000'+v).substr(c+4-b);
		});
	}
	return date.toString();
}

//格式化字符串
//formatStr('from {0} to {1}', 1, 100)
//formatStr('from {0} to {1}', [1, 100])
//formatStr('from {begin} to {end}', {begin:'A', end:'F'})
function formatStr(str, args){
	if($.type(arguments[1]) == 'array'){
		var p = arguments[1];
		return str.replace(/\{(\d+)\}/g, function(match, index){
			return p[parseInt(index)];
		});
	}else if($.type(arguments[1]) == 'object'){
		var p = arguments[1];
		return str.replace(/\{(.+?)\}/g, function(match, name){
			return p[name];
		});
	}else{
		var p = arguments;
		return str.replace(/\{(\d+)\}/g, function(match, index){
			return p[parseInt(index)+1];
		});
	}
}

/**
 * 封装地区选择下拉框组件，基于ligerComboBox的树模式，封装了一些实用功能
 * 用法：
 * 创建地区选择器
 * createRegionSelect("region_name","region_id",{selectBoxWidth:300});
 * 
 * @param displayId 用于下拉框的text组件，显示地区名称
 * @param valueId 用于下拉框的hidden组件，存储地区id
 * @param options 可选配置项
 * @return 创建的ligerComboBox对象
 */
function createRegionSelect(displayId, valueId, options){
	options = options || {};
	var p = {};
	$.extend(p, {
		defaultValue: '',
		defaultText: '---请选择---',
		initValue: '',
		valueField: 'id',
		textField: 'name',
		valueFieldID: valueId,
		width: 220,
		selectBoxWidth: 220,
		selectBoxHeight: 260,
		treeLeafOnly:false,
		isTreeLeaf: function(node){return (node.isParent!==true && node.isParent!=='true');},
		forbidTreeCancel:true,
		extendTop: false,
		onTreeAfterAppend: onTreeAfterAppend
	}, options);
	var ptree = {};
	$.extend(ptree, {
		idFieldName:'id',
		textFieldName:'name',
		checkbox: false,
		isExpandCurrent:false,
		isAsync:true,
		isLeaf: function(node){return (node.isParent!==true && node.isParent!=='true');}
	}, p.tree);
	p.tree = ptree;
	
	p.render = function(val, text){
		var g=this,p=g.options, tree=g.treeManager;
		var pn = tree.getDataByID(val);
		var showText = '';
		if(pn){
			showText = pn[ptree.textFieldName];
			pn = tree.getParent(pn);
			while(pn){
				showText = pn[ptree.textFieldName]+' > '+showText;
				pn = tree.getParent(pn);
			}
		}
		return showText;
	};
	
	//用于在初始化树时选中默认值-对异步加载的特殊处理
	function onTreeAfterAppend(pNode, newdata, tree){
		if(!this.initloaded && p.extendTop && newdata && newdata.length && newdata[0].id){
			tree.expand(newdata[0].id);
			this.initloaded = true;
		}
		if(this._region_inited)return true;
		var initid = this.getInitValue();
		if(!initid || initid.length<2 || initid.length<p.defaultValue.length){
			this._region_inited = true;
		}
		var pid = (pNode==null)?'':pNode.id;
		if(pid==''){
			if(newdata && newdata.length>0 && newdata[0].pid!=null){
				var exid = newdata[0].id;
				exid = initid.substr(0, exid.length);
				tree.expand(exid);//展开第一层
			}
		}else if(pid=='0' && initid.length>=4){
			tree.expand(initid.substr(0,2));
		}else if(pid.length==2 && initid.length>=6){
			tree.expand(initid.substr(0,4));
		}else if(pid.length==4 && initid.length>=8){
			tree.expand(initid.substr(0,6));
		}else if(pid.length==6 && initid.length>=11){
			tree.expand(initid.substr(0,8));
		}
		if(pid.length >= initid.length-2){this._region_inited = true;}
		var sn = tree.getSelected();
		if(sn && sn.data.id==initid){this._region_inited = true;}
	}
	
	if(!p.initValue){
		p.initValue = $('#'+valueId).val();
		p.initValue = p.initValue || '';
	}
	
	//创建下拉框
	var regionSelect = $("#"+displayId).ligerComboBox(p);
	//返回下拉框对象
	return regionSelect;
}
